<script setup>
import { ref, onMounted } from 'vue'
import tabBarConfig from '@/pages.json'

const props = defineProps({
  current: {
    type: String,
    default: 'home'
  }
})

// 从pages.json的tabBar配置创建tabs数组
const tabs = ref([])

onMounted(() => {
  // 初始化标签栏数据
  initTabBarData()
})

function initTabBarData() {
  const tabBarList = tabBarConfig.tabBar.list
  
  tabs.value = tabBarList.map(item => {
    // 提取pagePath中的id (例如从 pages/home/index 提取 home)
    const pathParts = item.pagePath.split('/')
    const id = pathParts.length > 1 ? pathParts[1] : pathParts[0]
    
    return {
      id,
      title: item.text,
      icon: item.iconPath,
      activeIcon: item.selectedIconPath,
      path: '/' + item.pagePath
    }
  })
}

function switchTab(path) {
  console.log('TabBar点击导航到:', path)
  
  // 使用switchTab进行tabBar页面间的跳转
  uni.switchTab({
    url: path,
    success: function() {
      console.log('TabBar导航成功')
    },
    fail: function(err) {
      console.error('TabBar导航失败', err)
    }
  })
}
</script>

<template>
  <view class="tab-bar">
    <view 
      v-for="tab in tabs" 
      :key="tab.id"
      class="tab-item"
      :class="{ active: current === tab.id }"
      @click="switchTab(tab.path)"
    >
      <image class="tab-icon" :src="current === tab.id ? tab.activeIcon : tab.icon" mode="aspectFit" />
      <text class="tab-title">{{ tab.title }}</text>
    </view>
  </view>
</template>

<style lang="scss" scoped>
.tab-bar
{
    position: fixed;
    right: 0;
    bottom: 0;
    left: 0;

    display: flex;

    height: 100rpx;

    background-color: #fff;
    box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, .05);
}

.tab-item
{
    display: flex;
    align-items: center;
    flex: 1;
    flex-direction: column;
    justify-content: center;

    .tab-icon
    {
        width: 48rpx;
        height: 48rpx;
        margin-bottom: 6rpx;
    }

    .tab-title
    {
        font-size: 24rpx;

        color: #999;
    }

    &.active
    {
        .tab-title
        {
            color: #1890ff;
        }
    }
}

</style>